<meta charset="UTF-8">
<div id="organ-structure" class="full" style="padding: 10px;">
    <div class="demo-spin-container" v-if="loading">
        <Spin size="large" fix></Spin>
    </div>
    <Modal v-model="modal" width="500" :transfer="false">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="ios-create-outline"></Icon>
            <span>{{$t('bgMgr.sharedDevice')}} - {{ groupName }}</span>
        </p>
        <Row style="margin: 10px 0">
            <i-col span="6" style="height: 100%;text-align:right;line-height:32px;">
                <i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("reportForm.selectAccount")}} : &nbsp;</i-col>
            <i-col span="14">
                <el-select v-model="createrToUser" :popper-append-to-body="popperAppendToBody" style="width:100%;line-height: 32px;height: 32px;" size="mini" filterable>
                    <el-option v-for="item in currentPageUserLists" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </i-col>
        </Row>
        <div slot="footer">
            <i-button type="primary" style="width: 100%" @click="sharedGroup">{{$t('header.submit')}}</i-button>
        </div>
    </Modal>
    <div class="full" style="position: relative;">
        <div style="position: absolute;top:0px;left:0px;right: 0px;height: 30px;">
            <h3 class="h3-title">{{$t("bgMgr.organStructure")}}</h3>
        </div>
        <div style="position: absolute;top:30px;left:0;right: 0px;bottom: 0px;border: 1px solid #e3e3e3;">
            <div style="position: absolute;top:0px;left:0;bottom: 0px;width: 300px;border-right: 1px solid #e3e3e3;">
                <div class="icon_example" style="margin-top:5px;text-align: center;">
                    <span class="user_icon"></span><span>{{$t("bgMgr.user")}}</span>
                    <span class="group_icon"></span><span>{{$t("bgMgr.group")}}</span>
                    <span class="device_icon"></span><span>{{$t("bgMgr.ordinaryDev")}}</span>
                    <span class="video_icon"></span><span>{{$t("bgMgr.videoDev")}}</span>
                </div>
                <div style="padding: 0 5px 5px 5px;">
                    <i-input v-model.trim="searchDeviceVal" style="width: 100%;" icon="ios-close-circle-outline" @on-click="cleanSearchVal"></i-input>
                </div>
                <div style="position: absolute;top:65px;left:0;bottom: 0px;right: 0px;overflow-y: auto;">
                    <ul id="ztree" class="ztree"></ul>
                </div>
            </div>
            <div style="position: absolute;top:0px;left:300px;bottom: 0px;right: 0px;">
                <div v-if="selectType =='user'">
                    <div style="margin-left: 20px;width: 740px;">
                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                <i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("reportForm.selectAccount")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <el-select v-model="createrToUser" :disabled="disabledInput" style="width:100%" size="mini" filterable>
                                    <el-option v-for="item in currentPageUserLists" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </i-col>
                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                <i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("user.username")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="username" :disabled="isEditUser"></i-input>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                &nbsp; {{$t("user.showname")}}: &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="showname" :disabled="disabledInput"></i-input>
                            </i-col>
                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                <i style="color: red;display: inline-block;">*</i> &nbsp;{{$t("user.userType")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model="usertype" :disabled="disabledInput">
                                    <i-option v-for="item in userTypeList" :value="item.type" :key="item.type">{{ item.name }}</i-option>
                                </i-select>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                <i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("user.password")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="password" :disabled="isEditUser"></i-input>
                            </i-col>
                        </Row>


                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                &nbsp;{{$t("user.corporateName")}} : &nbsp;
                            </i-col>
                            <i-col span="8">
                                <i-input v-model.trim="companyname" :disabled="disabledInput"></i-input>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                &nbsp;{{$t("user.name")}} : &nbsp;
                            </i-col>
                            <i-col span="8">
                                <i-input v-model.trim="cardname" :disabled="disabledInput"></i-input>
                            </i-col>
                        </Row>


                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                &nbsp;{{$t("user.phone")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="phone" :disabled="disabledInput"></i-input>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                &nbsp;{{$t("user.address")}} : &nbsp;
                            </i-col>
                            <i-col span="8">
                                <i-input v-model.trim="companyaddr" :disabled="disabledInput"></i-input>
                            </i-col>
                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                &nbsp;{{$t("header.qq")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="qq" :disabled="disabledInput"></i-input>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                &nbsp;{{$t("user.weChat")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="wechat" :disabled="disabledInput"></i-input>
                            </i-col>
                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">
                                &nbsp;{{$t("header.email")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="email" :disabled="disabledInput"></i-input>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("user.moreLanding")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model="multilogin" :disabled="disabledInput">
                                    <i-option value="1">{{$t("header.yes")}}</i-option>
                                    <i-option value="0">{{$t("header.no")}}</i-option>
                                </i-select>
                            </i-col>
                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="12" :offset="6">
                                <i-button style="width:100%" @click="handleEditUser" :disabled="disabledInput">{{$t("bgMgr.submit")}}</i-button>
                            </i-col>
                        </Row>
                    </div>
                </div>
                <div v-if="selectType =='group'">
                    <Row style="margin: 10px 0">
                        <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("group.groupName")}} : &nbsp;</i-col>
                        <i-col span="8">
                            <i-input v-model.trim="groupName" :disabled="selectedGroupId==0"></i-input>
                        </i-col>
                    </Row>
                    <Row style="margin: 10px 0 0 0" v-show="selectedGroupId==0">
                        <i-col span="8" :offset="4">
                            <Alert type="warning">
                                <h3>{{$t("device.editDefaultGroupNameTip")}}</h3>
                            </Alert>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col span="8" :offset="4">
                            <i-button type="primary" style="width: 100%" @click="handleEditGroupName" :disabled="selectedGroupId==0">{{$t("bgMgr.submit")}}</i-button>
                        </i-col>
                    </Row>
                </div>
                <div v-if="selectType =='device'">
                    <div style="width:740px;margin-left: 20px;">
                        <Row style="margin: 10px 0" v-if="userType < 4">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("reportForm.selectAccount")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <el-select v-model="createrToUser" style="width: 100%;" size="mini" filterable>
                                    <el-option v-for="item in currentPageUserLists" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </i-col>
                        </Row>
                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("user.grouping")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model.sync="groupid">
                                    <i-option v-for="item in groupsList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                                </i-select>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.sim")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="simnum"></i-input>
                            </i-col>
                        </Row>
                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("bgMgr.expirenotifytime")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <date-picker type="date" v-model="expirenotifytime" :disabled="disabledOverdueTime" style="width: 100%;"></date-picker>
                            </i-col>

                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("alarm.devName")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="devicename"></i-input>
                            </i-col>

                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("user.devType")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <!-- devicetype -->
                                <i-select v-model="devicetype" :disabled="isfree!==2">
                                    <i-option v-for="item in deviceTypeList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                                </i-select>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("alarm.devNum")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="deviceid" disabled></i-input>
                            </i-col>

                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("device.networkType")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model="teltype">
                                    <i-option value="1">{{$t("reportForm.maxSignal")}}32(2G)</i-option>
                                    <i-option value="2">{{$t("reportForm.maxSignal")}}64(2G)</i-option>
                                    <i-option value="3">{{$t("reportForm.maxSignal")}}32(3G)</i-option>
                                    <i-option value="4">{{$t("reportForm.maxSignal")}}32(4G)</i-option>
                                </i-select>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("manageTransfer.transferPlatform")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="forwardurl" disabled></i-input>
                            </i-col>
                        </Row>


                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.isUse")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model="deviceenable">
                                    <i-option value="0">{{$t("user.ban")}}</i-option>
                                    <i-option value="1">{{$t("user.allow")}}</i-option>
                                </i-select>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("device.tutelageUser")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-input v-model.trim="monitor"></i-input>
                            </i-col>
                        </Row>


                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("device.subEditor")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model="allowedit" :disabled="isAlloweditDisabled">
                                    <i-option value="0">{{$t("user.ban")}}</i-option>
                                    <i-option value="1">{{$t("user.allow")}}</i-option>
                                </i-select>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.allowLogin")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model="loginenable">
                                    <i-option value="0">{{$t("user.ban")}}</i-option>
                                    <i-option value="1">{{$t("user.allow")}}</i-option>
                                </i-select>
                            </i-col>
                        </Row>
                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("device.timeZone")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model="timezone">
                                    <i-option value="99">{{$t("device.automatic")}}</i-option>
                                    <i-option value="-12">-12</i-option>
                                    <i-option value="-11">-11</i-option>
                                    <i-option value="-10">-10</i-option>
                                    <i-option value="-9">-9</i-option>
                                    <i-option value="-8">-8</i-option>
                                    <i-option value="-7">-7</i-option>
                                    <i-option value="-6">-6</i-option>
                                    <i-option value="-5">-5</i-option>
                                    <i-option value="-4">-4</i-option>
                                    <i-option value="-3">-3</i-option>
                                    <i-option value="-2">-2</i-option>
                                    <i-option value="-1">-1</i-option>
                                    <i-option value="0">0</i-option>
                                    <i-option value="1">+1</i-option>
                                    <i-option value="2">+2</i-option>
                                    <i-option value="3">+3</i-option>
                                    <i-option value="4">+4</i-option>
                                    <i-option value="5">+5</i-option>
                                    <i-option value="6">+6</i-option>
                                    <i-option value="7">+7</i-option>
                                    <i-option value="8">+8</i-option>
                                    <i-option value="9">+9</i-option>
                                    <i-option value="10">+10</i-option>
                                    <i-option value="11">+11</i-option>
                                    <i-option value="12">+12</i-option>
                                    <i-option value="13">+13</i-option>
                                    <i-option value="14">+14</i-option>
                                </i-select>
                            </i-col>
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("device.calmileageway")}} : &nbsp;</i-col>
                            <i-col span="8">
                                <i-select v-model="calmileageway">
                                    <i-option value="0">{{$t("device.automatic")}}</i-option>
                                    <i-option value="1">{{$t("device.devCalc")}}</i-option>
                                    <i-option value="2">{{$t("device.platformCalc")}}</i-option>
                                </i-select>
                            </i-col>
                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("monitor.remarks")}} : &nbsp;</i-col>
                            <i-col span="20">
                                <i-input v-model.trim="remark" type="textarea" :rows="2"></i-input>
                            </i-col>
                        </Row>

                        <Row style="margin: 10px 0">
                            <i-col span="12" :offset="7">
                                <i-button style="width: 100%" @click="handleEditDevice">{{$t("bgMgr.submit")}}</i-button>
                            </i-col>
                        </Row>
                    </div>
                </div>
                <div style="position: absolute;bottom:0px;left:0px;right: 0px;height: 45px;border-top: 1px solid #e3e3e3;">
                    <div style="width: 100%;height: 100%;line-height: 45px;display: flex;justify-content: center;align-items: center;" v-show="selectType =='user'">
                        <i-button type="primary" @click="addUser" style="margin: 0 10px;">{{$t("bgMgr.addUser")}}</i-button>
                        <i-button type="primary" @click="addGroup" style="margin: 0 10px;">{{$t("bgMgr.addGroup")}}</i-button>
                        <Poptip trigger="click" :title="$t('message.confirmDel')" confirm @on-ok="deleteUser">
                            <i-button type="error" style="margin: 0 10px;">{{$t("bgMgr.deleteUser")}}</i-button>
                        </Poptip>
                        <i-button type="info" @click="refreshzTree" style="margin: 0 10px;">{{$t("bgMgr.refreshArchitecture")}}</i-button>
                    </div>
                    <div style="width: 100%;height: 100%;line-height: 45px;display: flex;justify-content: center;align-items: center;" v-show="selectType =='group'">
                        <Poptip trigger="click" :title="$t('message.confirmDel')" confirm @on-ok="deleteGroup">
                            <i-button :disabled="selectedGroupId==0" type="error" style="margin: 0 10px;">{{$t("bgMgr.deleteGroup")}}</i-button>
                        </Poptip>
                        <i-button type="info" @click="refreshzTree" style="margin: 0 10px;">{{$t("bgMgr.refreshArchitecture")}}</i-button>
                        <i-button type="info" @click="modal=true" style="margin: 0 10px;" v-show="selectedGroupId!=0">{{$t("bgMgr.sharedDevice")}}</i-button>
                    </div>
                    <div style="width: 100%;height: 100%;line-height: 45px;display: flex;justify-content: center;align-items: center;" v-show="selectType =='device'">
                        <Poptip trigger="click" :title="$t('message.confirmDel')" confirm @on-ok="deleteDevice">
                            <i-button type="error" style="margin: 0 10px;">{{$t("bgMgr.deleteDevice")}}</i-button>
                        </Poptip>
                        <i-button type="info" @click="refreshzTree" style="margin: 0 10px;">{{$t("bgMgr.refreshArchitecture")}}</i-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    vueInstanse = new Vue({
        el: "#organ-structure",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            modal: false,
            userType: localStorage.getItem('userType'),
            searchDeviceVal: '',
            selectType: null,
            groupName: '',
            selectedGroupId: null,
            selectedUserName: null,
            selectedDeviceid: null,

            currentPageUserLists: [],

            popperAppendToBody: false,
            isShowMatchDev: false,
            createrToUser: '',
            groupid: '',
            password: '',
            groupsList: [],
            simnum: '',
            expirenotifytime: null,
            devicename: '',
            devicetype: null,
            deviceTypeList: [],
            deviceid: '',
            teltype: '',
            deviceenable: '',
            monitor: '',
            allowedit: '',
            loginenable: '',
            timezone: '8',
            calmileageway: '0',
            isfree: 0,
            forwardurl: "",
            remark: '',

            userTypeList: [],
            username: "",
            showname: "",
            usertype: "",
            showname: "",
            companyname: "",
            cardname: "",
            phone: "",
            companyaddr: "",
            qq: "",
            wechat: "",
            email: "",
            multilogin: "",
            isEditUser: true,
            isEditGroup: true,

        },
        methods: {
            addUser: function() {
                var newVal = this.selectedUserName;
                this.isEditUser = false;
                this.createrToUser = newVal;
                var index = -1;
                this.list.forEach(function(item, idx) {
                    if (item.username === newVal) {
                        index = idx;
                    }
                });
                this.usertype = "";
                if (index != -1) {
                    this.setUserTypeByUser(this.list[index].usertype, false);
                }
                this.setUserInfo({
                    multilogin: 1
                });
            },
            addGroup: function() {
                this.isEditGroup = false;
                this.selectType = 'group';
                this.groupName = '';
                this.selectedGroupId = -11;
                this.createrToUser = this.selectedUserName;
            },
            deleteUser: function() {
                var me = this;
                var url = myUrls.delUser();
                var data = {
                    usernames: [this.selectedUserName]
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        rootuser = null;
                        isNeedRefresh = true;
                        me.$Message.success(me.$t("message.deleteSucc"));
                        me.removeNodes();
                        GlobalOrgan.getInstance().removeUser(data.usernames[0]);
                        me.reloadTreeData(false);
                        me.selectType = null;
                        var idx = globalUserList.indexOf(data.usernames[0]);
                        if (idx != -1) {
                            globalUserList.splice(idx, 1);
                        }
                    } else if (resp.status == 1) {

                        me.$Message.error(me.$t("message.deleteUserTips") + resp.count);
                    } else {
                        me.$Message.error(resp.cause);
                    }
                });
            },
            deleteGroup: function() {
                var me = this;
                var url = myUrls.deleteGroup();
                var data = {
                    groupid: this.selectedGroupId,
                    username: this.selectedUserName,
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        rootuser = null;
                        isNeedRefresh = true;
                        me.$Message.success(me.$t("message.deleteSucc"));
                        me.removeNodes();
                        GlobalOrgan.getInstance().removeGroup(data.username, data.groupid);
                        me.reloadTreeData();
                        me.selectType = null;

                    } else {
                        me.$Message.error(resp.cause);
                    }
                });
            },
            sharedGroup: function() {
                var me = this;
                var url = myUrls.addShareGroup();
                if (globalUserList.indexOf(this.createrToUser) != -1) {
                    var data = {
                        fromcreater: this.selectedUserName,
                        tocreater: this.createrToUser,
                        groupid: this.selectedGroupId,
                        groupname: this.groupName,
                    }
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status == 0) {
                            me.modal = false;
                            me.$Message.success(me.$t('message.addSucc'));
                        } else {
                            me.$Message.error(me.$t('message.addFail'));
                        }
                    })
                }
            },

            reloadTreeData: function(isRefreshUi) {
                this.treeDeviceList = [this.castUsersTreeToDevicesTree(GlobalOrgan.getInstance().globalOrganData, true, false)];
                if (isRefreshUi) {
                    if (this.zTreeObj) {
                        this.zTreeObj.destroy();
                    }
                    this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, this.treeDeviceList);
                }
            },

            deleteDevice: function() {
                var me = this;
                var url = myUrls.deleteDevice();
                var deviceid = this.selectedDeviceid;
                var data = {
                    deviceid: deviceid
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        rootuser = null;
                        isNeedRefresh = true;
                        if (deviceid == globalDeviceId) {
                            globalDeviceId = "";
                            vRoot.$store.commit('currentDeviceId', "");
                        }

                        me.$Message.error(me.$t("message.deleteSucc"));
                        me.removeNodes();
                        GlobalOrgan.getInstance().removeDevice(me.selectedUserName, me.selectedGroupId, data.deviceid);
                        me.reloadTreeData(false);
                        me.selectType = null;

                    } else {
                        me.$Message.error(me.$t("message.deleteFail"));
                    }
                });
            },
            removeNodes: function() {
                var nodes = this.zTreeObj.getCheckedNodes();
                if (nodes && nodes.length) {
                    this.zTreeObj.removeNode(nodes[0]);
                    this.zTreeObj.refresh();
                }
            },
            handleEditUser: function() {
                var me = this;
                var isEditUser = this.isEditUser;
                var userType = this.usertype;

                if (userType == "") {
                    this.$Message.error('请选择用户类型');
                    return;
                }

                if (globalUserList.indexOf(this.createrToUser) == -1) {
                    me.$Message.error(me.$t("message.selectCorrectAccount"));
                    return;
                }

                var data = {
                    creater: this.createrToUser,
                    username: this.username,
                    usertype: userType,
                }

                if (isEditUser) {
                    var url = myUrls.editUser();
                } else {
                    var url = myUrls.addUser();
                    if (this.password == "") {
                        this.$Message.error('请填写用户密码');
                        return;
                    }
                    data.password = $.md5(this.password);
                }

                data.multilogin = Number(this.multilogin);
                this.qq ? data.qq = this.qq : "";
                this.email ? data.email = this.email : "";
                this.phone ? data.phone = this.phone : "";
                this.wechat ? data.wechat = this.wechat : "";
                this.companyname ? data.companyname = this.companyname : null;
                this.cardname ? data.cardname = this.cardname : null;
                this.companyaddr ? data.companyaddr = this.companyaddr : null;
                this.showname ? data.showname = this.showname : null;

                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        rootuser = null;
                        isNeedRefresh = true;
                        if (!isEditUser) {
                            me.zTreeObj.addNodes(me.parentNode, {
                                name: data.username,
                                username: data.username,
                                nocheck: false,
                                icon: myUrls.viewhost + "zTreeStyle/img/diy/account.svg",
                                pId: me.parentNode.id,
                                children: [],
                            });
                            globalUserList.push(data.username);
                            GlobalOrgan.getInstance().addUser(data);
                            me.currentPageUserLists.push({
                                label: data.username,
                                value: data.username,
                            });
                            me.reloadTreeData(true);
                            me.getUserInfoList();
                        } else {
                            GlobalOrgan.getInstance().editUser(me.oldCreater, data);
                            me.treeDeviceList = [me.castUsersTreeToDevicesTree(GlobalOrgan.getInstance().globalOrganData, true, false)];
                            if (me.oldCreater !== data.creater) {
                                me.reloadTreeData(true);
                            }
                        }
                        me.$Message.success(me.$t(isEditUser ? "message.changeSucc" : "message.addSucc"));
                    } else if (resp.status == 1) {
                        if (!isEditUser) {
                            me.$Message.error(isZh ? '用户已存在' : 'User already exists');
                        }
                    } else {
                        me.$Message.error(me.$t(isEditUser ? "message.changeFail" : "message.addFail") + ' ' + resp.cause);
                    }
                });

            },
            handleEditDevice: function() {
                var me = this;
                var url = myUrls.editDevice();
                if (this.expirenotifytime == "") {
                    me.$Message.error(me.$t("message.plSelectTime"));
                    return;
                }

                var data = {
                    deviceid: this.deviceid,
                    devicetype: this.devicetype,
                    expirenotifytime: new Date(this.expirenotifytime).getTime(),
                    loginenable: Number(this.loginenable),
                    deviceenable: Number(this.deviceenable),
                    allowedit: Number(this.allowedit),
                    timezone: Number(this.timezone),
                    calmileageway: Number(this.calmileageway),
                };

                if (this.devicename) {
                    data.devicename = this.devicename;
                };
                if (this.teltype) {
                    data.teltype = Number(this.teltype);
                };


                if (this.simnum !== "") {
                    data.simnum = this.simnum;
                };
                if (this.remark !== "") {
                    data.remark = this.remark;
                };

                if (this.groupid !== "" && this.groupsList.length) {
                    data.groupid = this.groupid;
                } else {
                    data.groupid = 0;
                };

                data.monitor = this.monitor;

                // this.forwardurl && (data.forwardurl = this.forwardurl);

                if (globalUserList.indexOf(this.createrToUser) == -1) {
                    me.$Message.error(me.$t("message.selectCorrectAccount"));
                    return;
                }

                if (this.userType < 4) {
                    data.creater = this.createrToUser;
                } else {
                    data.creater = userName;
                }

                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        rootuser = null;
                        isNeedRefresh = true;
                        me.parentNode.name = data.devicename; // 修改name属性
                        me.parentNode.devicename = data.devicename; // 修改name属性
                        me.zTreeObj.updateNode(me.parentNode); // 调用updateNode修改属性，一定要加这一句，不然reAsyncChildNodes没有任何反应
                        me.zTreeObj.reAsyncChildNodes(me.parentNode, 'refresh', false);
                        me.$Message.success(me.$t("message.changeSucc"));
                        GlobalOrgan.getInstance().editDevice(me.selectedUserName, me.selectedGroupId, data);
                        if (me.oldCreater !== data.creater || data.groupid !== editObject.groupid) {
                            me.refreshzTree();
                        }
                    } else if (resp.status = -1) {
                        me.$Message.error(me.$t("message.changeFail"));
                    }
                });
            },
            getUserInfoList: function(callback) {
                var me = this;
                var url = myUrls.queryUser();
                utils.sendAjax(url, {
                    username: userName
                }, function(resp) {

                    var list = [];
                    if (resp.status == 0 && resp.userlists != null) {
                        resp.userlists.forEach(function(item) {
                            if (item.usertype <= 4) {
                                list.push({
                                    username: item.username,
                                    usertype: item.usertype
                                })
                            }
                        });
                    }
                    list.push({
                        username: userName,
                        usertype: vstore.state.userType
                    })
                    me.list = list;
                    callback && callback();
                });
            },
            handleEditGroupName: function() {
                if (this.groupName == "") {
                    this.$Message.error(this.$t("message.fillGroupNameTip"));
                    return;
                };
                me = this;
                if (this.isEditGroup) {
                    var url = myUrls.editGroup();

                    var data = {
                        groupid: this.selectedGroupId,
                        groupname: this.groupName,
                    };
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status == 0) {
                            me.parentNode.name = data.groupname + '(' + me.parentNode.children.length + ')'; // 修改name属性
                            me.parentNode.groupname = data.groupname; // 修改name属性
                            me.zTreeObj.updateNode(me.parentNode); // 调用updateNode修改属性，一定要加这一句，不然reAsyncChildNodes没有任何反应
                            me.zTreeObj.reAsyncChildNodes(me.parentNode, 'refresh', false);
                            GlobalOrgan.getInstance().editGroup(me.selectedUserName, data);
                            me.reloadTreeData(false);
                            me.$Message.success(me.$t("message.changeSucc"));
                        } else {
                            me.$Message.error(resp.cause);
                        }
                    });
                } else {
                    var url = myUrls.addGroup();
                    var data = {
                        groupname: this.groupName,
                        creater: this.createrToUser
                    };
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status == 0) {
                            rootuser = null;
                            me.zTreeObj.addNodes(me.parentNode, {
                                name: me.groupName,
                                groupid: resp.groupid,
                                groupname: me.groupName,
                                pId: me.parentNode.id,
                                icon: myUrls.viewhost + "zTreeStyle/img/diy/group.svg",
                                children: [],
                            });
                            data.groupid = resp.groupid;
                            data.devices = [];
                            GlobalOrgan.getInstance().addGroup(data.creater, data);
                            me.groupsList = GlobalOrgan.getInstance().getGroupListByUserName(data.creater);
                            me.reloadTreeData(false);
                            me.$Message.success(me.$t("message.addSucc"));
                        } else {
                            me.$Message.error(resp.cause);
                        }
                    });
                }
            },
            getDeviceList: function(selectedDeviceid) {
                var me = this;
                var url = myUrls.queryDeviceById();
                utils.sendAjax(url, {
                    deviceid: selectedDeviceid,
                }, function(resp) {
                    if (resp.status == 0 && resp.device != null) {
                        editObject = resp.device;
                        me.setDeviceData();
                    }
                });
            },
            getDeviceType: function() {
                var me = this;
                var deviceTypes = vstore.state.deviceTypes;
                for (var key in deviceTypes) {
                    var item = deviceTypes[key];
                    if (item) {
                        var label = item.typename;
                        if (item.remark) {
                            label += "(" + (isZh ? item.remark : item.remarken) + ")";
                        }
                        me.deviceTypeList.push({
                            value: item.devicetypeid,
                            label: label
                        });
                    }
                }
            },
            setDeviceData: function() {

                var me = this;
                me.deviceid = editObject.deviceid;
                me.simnum = editObject.simnum;
                me.expirenotifytime = new Date(editObject.expirenotifytime);
                me.devicename = editObject.devicename;
                me.devicetype = editObject.devicetype;
                me.loginenable = editObject.loginenable + "";
                me.deviceenable = "" + editObject.deviceenable;
                // me.forwardurl = editObject.forwardurl;
                me.isfree = editObject.isfree;
                me.monitor = editObject.monitor;
                me.timezone = String(editObject.timezone);
                me.calmileageway = String(editObject.calmileageway);
                me.teltype = String(editObject.teltype);
                me.allowedit = String(editObject.allowedit);
                me.createrToUser = editObject.creater;
                me.remark = editObject.remark;
                this.oldCreater = me.createrToUser;

                var record = me.forwards[editObject.forwardid];
                me.forwardurl = record ? record.servername : '';

            },

            queryUserDetail: function(username) {
                var me = this;
                var url = myUrls.queryUserDetail();
                utils.sendAjax(url, {
                    username: username
                }, function(resp) {
                    me.usertype = resp.usertype;
                    me.setUserInfo(resp);
                })
            },
            queryDevicesTree: function() {
                var me = this;
                this.loading = true;

                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.loading = false;
                    me.setTreeDataList(rootuser);
                })
            },
            queryGroupsByUserName: function(userName) {
                var me = this;
                me.groupsList = GlobalOrgan.getInstance().getGroupListByUserName(userName);
                if (me.groupid === undefined) {
                    me.groupid = editObject.groupid;
                }
            },
            setTreeDataList: function(rootuser) {
                this.treeDeviceList = [this.castUsersTreeToDevicesTree(rootuser, true, false)];
                var me = this;
                this.setting = {
                    check: {
                        enable: true,
                        chkStyle: "radio",
                        radioType: "all"
                    },
                    callback: {
                        onCheck: function(id, ztree) {
                            var nodes = me.zTreeObj.getCheckedNodes();
                            if (nodes.length) {
                                me.parentNode = nodes[0];
                                var node = nodes[0];
                                var username = '';
                                var groupid = 0;
                                if (node.username !== undefined) {
                                    username = node.username;
                                    me.selectType = 'user';
                                    me.queryUserDetail(username);
                                    var parentNode = node.getParentNode();
                                    me.createrToUser = parentNode ? parentNode.username : userName;
                                    me.oldCreater = me.createrToUser;
                                    me.isEditUser = true;
                                    me.password = '';
                                    me.list.forEach(function(item, idx) {
                                        if (item.username == me.createrToUser) {
                                            me.usertype = item.usertype;
                                            me.setUserTypeByUser(item.usertype, userName == username);
                                        }
                                    });

                                } else if (node.groupid !== undefined) {
                                    var parentNode = node.getParentNode();
                                    username = parentNode.username;
                                    groupid = node.groupid;
                                    me.groupName = node.groupname;
                                    me.selectType = 'group';
                                    me.isEditGroup = true;
                                } else {
                                    me.selectType = 'device';
                                    var parentNode = node.getParentNode();
                                    var pparentNode = parentNode.getParentNode();
                                    // console.log('parentNode', parentNode)
                                    username = pparentNode.username;
                                    groupid = parentNode.groupid;
                                    me.groupid = groupid;
                                    me.selectedDeviceid = node.deviceid;
                                    me.getDeviceList(node.deviceid);
                                }
                                me.selectedGroupId = groupid;
                                me.selectedUserName = username;
                            } else {
                                if (me.parentNode) {
                                    me.zTreeObj.checkNode(me.parentNode, true, true)
                                }
                                // me.selectType = null;
                                // me.selectedGroupId = null;
                                // me.selectedUserName = null;
                            }
                        }
                    },
                };
                this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, this.treeDeviceList);

                me.selectedRootNode();

            },

            selectedRootNode: function() {
                this.selectType = 'user';
                this.selectedUserName = userName;
                this.parentNode = this.zTreeObj.getNodes()[0];
                this.queryUserDetail(userName);
            },
            getDeviceListGroups: function(groups, isNeedDevice, username, isNeedRadio) {
                var groupsList = [],
                    me = this;
                if (groups != null) {

                    for (var i = 0; i < groups.length; ++i) {
                        var group = groups[i];
                        var groupname = group.groupid == 0 ? vRoot.$t('monitor.defaultGroup') : group.groupname;

                        var groupObj = {
                            groupid: group.groupid,
                            name: groupname,
                            groupname: groupname,
                            icon: myUrls.viewhost + "zTreeStyle/img/diy/group.svg"
                        }
                        if (isNeedDevice) {
                            groupObj.render = utils.renderGroup;

                        } else {
                            groupObj.totalCount = group.devices.length;
                            groupObj.name = groupname + '(' + group.devices.length + ')';
                        }
                        if (isNeedDevice && group.devices) {
                            groupObj.totalCount = group.devices.length;
                            groupObj.children = [];
                            groupObj.name = groupname + '(' + group.devices.length + ')';
                            group.devices.forEach(function(device) {
                                groupObj.children.push({
                                    deviceid: device.deviceid,
                                    name: device.devicename,
                                    icon: utils.getzTreeDeviceIcon(device)
                                });
                                utils.deviceInfos[device.deviceid] = {
                                    deviceid: device.deviceid,
                                    devicename: device.devicename,
                                    username: username,
                                    groupid: group.groupid,
                                    groupname: groupname,
                                    forwardid: device.forwardid,
                                }
                            });
                        }
                        groupsList.push(groupObj);
                    }
                }

                if (groupsList.length == 0) {
                    groupsList.push({
                        name: isZh ? '默认组(0)' : 'Default Group(0)',
                        groupname: isZh ? '默认组' : 'Default',
                        groupid: 0,
                        totalCount: 0,
                        children: [],
                        icon: myUrls.viewhost + "zTreeStyle/img/diy/group.svg"
                    });
                }
                return groupsList;
            },
            doCastUsersTreeToDevicesTree: function(usersTrees, isNeedDevice, isNeedRadio) {
                var devicesTreeRecord = [];
                if (usersTrees != null && usersTrees.length > 0) {
                    for (var i = 0; i < usersTrees.length; ++i) {
                        var usersTree = usersTrees[i];
                        var username = usersTree.username;
                        var subusers = usersTree.subusers;
                        var currentsubDevicesTreeRecord = {
                            name: username,
                            username: username,
                            nocheck: isNeedRadio,
                            icon: myUrls.viewhost + "zTreeStyle/img/diy/account.svg",
                            showname: usersTree.showname
                        };
                        var deviceListGroups = this.getDeviceListGroups(usersTree.groups, isNeedDevice, username, isNeedRadio);
                        if (username != null && subusers != null && subusers.length > 0) {
                            var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers, isNeedDevice, isNeedRadio);
                            subDevicesTreeRecord = deviceListGroups.concat(subDevicesTreeRecord);
                            currentsubDevicesTreeRecord.children = subDevicesTreeRecord;
                        } else {
                            currentsubDevicesTreeRecord.children = deviceListGroups;

                        }
                        var totalCount = 0;
                        if (currentsubDevicesTreeRecord.children) {
                            for (var j = 0; j < currentsubDevicesTreeRecord.children.length; ++j) {
                                totalCount += currentsubDevicesTreeRecord.children[j].totalCount;
                            }
                        }
                        currentsubDevicesTreeRecord.totalCount = totalCount;
                        currentsubDevicesTreeRecord.name = username + "(" + totalCount + ")";

                        devicesTreeRecord.push(currentsubDevicesTreeRecord);
                    }
                }
                return devicesTreeRecord;
            },
            castUsersTreeToDevicesTree: function(devicesTreeRecord, isNeedDevice, isNeedRadio) {
                var iViewTree = {
                    open: true,
                    nocheck: false,
                    checked: true,
                    icon: myUrls.viewhost + "zTreeStyle/img/diy/1_open.png"
                };
                if (devicesTreeRecord != null) {
                    var username = devicesTreeRecord.username;
                    var subusers = devicesTreeRecord.subusers;
                    iViewTree.name = username;
                    iViewTree.username = username;
                    var deviceListGroups = this.getDeviceListGroups(devicesTreeRecord.groups, isNeedDevice, username, isNeedRadio);
                    if (username != null && subusers != null && subusers.length > 0) {
                        var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers, isNeedDevice, isNeedRadio);
                        iViewTree.children = deviceListGroups.concat(subDevicesTreeRecord);
                    } else {
                        iViewTree.children = deviceListGroups;
                    }
                    var totalCount = 0;
                    if (iViewTree.children) {
                        for (var i = 0; i < iViewTree.children.length; ++i) {
                            totalCount += iViewTree.children[i].totalCount;
                        }
                    }
                    iViewTree.name = username + "(" + totalCount + ")";
                }
                return iViewTree;
            },
            variableDeepSearch: function(treeDataFilter, searchWord, limitcount) {
                searchWord = searchWord.toLowerCase();
                var childTemp = [];
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var copyItem = null;
                    var item = treeDataFilter[i];
                    if (item != null) {

                        var isFound = false;
                        if (item.name.toLowerCase().indexOf(searchWord) != -1 || (item.showname && item.showname.toLowerCase().indexOf(searchWord) != -1) || (item.deviceid && item.deviceid.toLowerCase().indexOf(searchWord) != -1)) {
                            copyItem = item;
                            copyItem.open = false;
                            isFound = true;
                        }
                        if (isFound == false && item.children && item.children.length > 0) {
                            var rs = that.variableDeepSearch(item.children, searchWord, limitcount);
                            if (rs && rs.length > 0) {
                                copyItem = deepClone(item);
                                copyItem.children = rs;
                                copyItem.open = true;
                                isFound = true;
                            }
                        }
                        if (isFound == true) {
                            limitcount++;
                            childTemp.push(copyItem);

                            if (limitcount > 1000) {
                                break;
                            }
                        }
                    }
                }
                return childTemp;
            },
            setUserTypeByUser: function(userType, isShowMe) {
                var allUserTypes = deepClone(vstore.state.userTypeDescrList);
                var filteredUserTypes = [];
                allUserTypes.forEach(function(userItem) {
                    //filter the little admin and only the admin 
                    if (isShowMe) {
                        if (userItem.type >= userType && userItem.type < 20) {
                            filteredUserTypes.push(userItem);
                        }
                    } else {
                        if (userItem.type > userType && userItem.type < 20) {
                            filteredUserTypes.push(userItem);
                        }
                    }

                });
                this.userTypeList = filteredUserTypes;
            },
            setUserInfo: function(userInfo) {
                this.username = userInfo.username;
                this.qq = userInfo.qq;
                this.email = userInfo.email;
                this.phone = userInfo.phone;
                this.wechat = userInfo.wechat;
                this.multilogin = String(userInfo.multilogin);
                this.companyname = userInfo.companyname;
                this.cardname = userInfo.cardname;
                this.companyaddr = userInfo.companyaddr;
                this.showname = userInfo.showname;
            },
            refreshzTree: function() {
                this.selectType = null;
                GlobalOrgan.getInstance().globalOrganData = null;
                GlobalOrgan.getInstance().isRequesting = false;
                this.queryDevicesTree();
            },
            queryForwardParams: function() {
                var me = this;
                var url = myUrls.queryForwardParams();
                me.copyForwards = [];
                utils.sendAjax(url, {
                    creater: null,
                    keyword: '',
                }, function(resp) {

                    me.forwards = {};
                    if (resp.forwards != null) {
                        resp.forwards.forEach(function(item) {
                            me.forwards[item.forwardid] = item;
                        })
                    }

                });
            },
            cleanSearchVal: function() {
                if (this.searchDeviceVal != '') {
                    this.searchDeviceVal = '';
                }
            }
        },
        computed: {
            disabledInput: function() {
                return (userName == this.selectedUserName) && this.isEditUser;
            },
            disabledOverdueTime: function() {
                return this.userType > 4;
            },
            isAlloweditDisabled: function() {
                return !(Number(this.userType) <= 1);
            },
        },
        watch: {
            searchDeviceVal: function(newVal) {
                if (newVal === '') {
                    this.treeDeviceList[0].open = true;
                    this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, this.treeDeviceList);
                } else {
                    var limitcount = 0;
                    var data = this.variableDeepSearch(this.treeDeviceList, newVal, limitcount);
                    if (data.length == 0) {
                        data.push({
                            name: isZh ? '无数据' : 'No data',
                            nocheck: true
                        })
                    }
                    this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, data);
                }

            },
            createrToUser: function(newVal) {
                console.log('newVal', newVal);
                console.log('   this.list', this.list);
                if (globalUserList.indexOf(newVal) != -1) {
                    try {
                        this.queryGroupsByUserName(newVal);
                        // var index = -1;
                        // this.list.forEach(function(item, idx) {
                        //     if (item.username === newVal) {
                        //         index = idx;
                        //     }
                        // });
                        // this.usertype = "";
                        // if (index != -1) {
                        //     var item = this.list[index];
                        //     this.setUserTypeByUser(item.usertype, false);
                        // } else {
                        //     this.userTypeList = [];
                        // }
                    } catch (error) {
                        console.log('error', error);
                    }

                } else {
                    this.groupsList = [];
                    this.groupid = 0;
                }
            }
        },
        destroyed: function() {
            this.zTreeObj.destroy();
        },
        mounted: function() {
            var me = this;
            utils.deviceInfos = {};
            var currentPageUserLists = [];
            globalUserList.forEach(function(item) {
                currentPageUserLists.push({
                    label: item,
                    value: item,
                })
            });

            me.getUserInfoList(function() {
                this.createrToUser = userName;
                this.currentPageUserLists = currentPageUserLists;
                this.treeDeviceList = [];
                me.queryForwardParams();
                me.getDeviceType();
                me.setUserTypeByUser(me.userType, true);
                me.queryDevicesTree();
            });

        },
    })
</script>